package zhieasy.cn.common.utils;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * CMD执行
 * @author zouchanglin
 */
public class CmdScriptUtils {
    private static final Runtime runtime = Runtime.getRuntime();

    public static String execCmd(String[] arguments){
        StringBuilder buffer = new StringBuilder();
        try {
            Process process = runtime.exec(arguments);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                buffer.append(line).append("\n");
            }
            in.close();
            int re = process.waitFor();
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ERROR!!!";
    }


    public static String execCmd(String cmd, File dir) throws Exception {
        StringBuilder result = new StringBuilder();

        Process process = null;
        BufferedReader bufferedReader = null;
        BufferedReader bufferedReaderError = null;

        try {
            process = runtime.exec(cmd, null, dir);
            process.waitFor();

            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            bufferedReaderError = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line).append('\n');
            }

            while ((line = bufferedReaderError.readLine()) != null) {
                result.append(line).append('\n');
            }
        } finally {
            closeStream(bufferedReader);
            closeStream(bufferedReaderError);

            if (process != null) {
                process.destroy();
            }
        }

        return result.toString();
    }

    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
                // nothing
            }
        }
    }
}
